<script setup lang="ts">
import { computed, h, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/userStore.ts'
import { routes } from '@/router/routes.ts'
import {
  HomeOutlined,
  UserOutlined,
  DollarOutlined,
  ShoppingCartOutlined,
} from '@ant-design/icons-vue'

const router = useRouter()
const userStore = useUserStore()

// 当前选中菜单
const current = ref<string[]>([])

// 菜单项
const items = computed(() => {
  return routes
    .filter((item) => {
      if (item?.meta?.hidden) {
        return false
      }
      if (item.meta?.access && item.meta?.access === 'admin') {
        const role = userStore.loginUser.role
        if (role !== 0) {
          return false
        }
      }
      return true
    })
    .map((item) => {
      // 处理普通路由
      if (item.name === '主页') {
        return {
          key: item.path,
          icon: () => h(HomeOutlined),
          label: item.name,
          title: item.name,
        }
      } else if (item.name === '用户管理') {
        return {
          key: item.path,
          icon: () => h(UserOutlined),
          label: item.name,
          title: item.name,
        }
      } else if (item.name === '商品管理') {
        return {
          key: item.path,
          icon: () => h(DollarOutlined),
          label: item.name,
          title: item.name,
        }
      } else if (item.name === '我的购物车') {
        return {
          key: item.path,
          icon: () => h(ShoppingCartOutlined),
          label: item.name,
          title: item.name,
        }
      }
    })
})

const doMenuClick = ({ key }: { key: string }) => {
  const fullPath = key.startsWith('/') ? key : `/admin/${key}`
  router.push({
    path: fullPath,
  })
}

// 监听路由变化，更新当前选中菜单
router.afterEach((to) => {
  current.value = [to.path]
})
</script>

<template>
  <div id="global-sider">
    <a-layout-sider width="200" v-if="userStore.loginUser.id" breakpoint="lg" collapsed-width="0">
      <a-menu v-model:selectedKeys="current" mode="inline" :items="items" @click="doMenuClick" />
    </a-layout-sider>
  </div>
</template>

<style scoped></style>
